package com.ctgu.admin.system.controller;

import com.ctgu.admin.system.domain.Article;
import com.ctgu.admin.system.domain.Information;
import com.ctgu.admin.system.domain.Payment;
import com.ctgu.admin.system.service.ArticleService;
import com.ctgu.admin.system.service.EmailService;
import com.ctgu.admin.system.service.InformationService;
import com.ctgu.admin.system.service.PaymentService;
import com.ctgu.admin.system.validator.PaymentValid;
import com.ctgu.common.enums.StatusEnum;
import com.ctgu.common.utils.EntityBeanUtil;
import com.ctgu.common.utils.ResultVoUtil;
import com.ctgu.common.utils.StatusUtil;
import com.ctgu.common.vo.ResultVo;
import com.ctgu.component.shiro.ShiroUtil;
import com.ctgu.modules.system.domain.User;
import com.ctgu.modules.system.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 该类负责支付信息的封装
 */
@Controller
@RequestMapping("/system/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private InformationService informationService;

    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("system:payment:index")
    public String index(Model model, Payment payment) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("title", match -> match.contains())
                .withMatcher("articleID", match -> match.contains())
                .withMatcher("userID", match -> match.contains());

        // 获取数据列表
        Example<Payment> example = Example.of(payment, matcher);
        Page<Payment> list = paymentService.getPageList(example);


        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/system/payment/index";
    }

    /**
     * 查看我的稿费界面
     */
    @GetMapping("/myPayment")
    public String toMyPayment(Model model){
        User user = ShiroUtil.getSubject();
        List<Payment> list = paymentService.getAllPaymentByUserID(user);
        model.addAttribute("paymentList",list);
        model.addAttribute("user",user);
        return "/userPage/myPayment";
    }

    //设置某一篇文章可以获得的稿费
    @GetMapping("/setPayment")
    @ResponseBody
    public Map<String,String> setOneArticlePayment(@RequestParam(value = "money", required = true)Integer money,
                                                   @RequestParam(value = "article_id", required = true)Long article_id){
        Map<String,String> result = new HashMap<String,String>();
        Article article=articleService.getById(article_id);

        Payment payment=new Payment();
        if(article.getPayment()!=null)
            payment = article.getPayment();
        payment.setArticleID(article);
        payment.setMoney(money);

        //之前的固定方法删除
        User user = article.getCreateBy();
        payment.setUserID(user);
        payment.setTitle(article.getTitle());
        payment.setPayMethod(user.getPayAddress());


        paymentService.save(payment);
        article.setPayment(payment);    //更新文章表中的信息
        articleService.save(article);

        result.put("msg","设置成功");
        return result;
    }


    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    public String toAdd() {
        return "/system/payment/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    public String toEdit(@PathVariable("id") Payment payment, Model model) {
        model.addAttribute("payment", payment);
        return "/system/payment/add";
    }

    /**
     * 保存添加/修改的数据
     */
    @PostMapping("/save")
    @ResponseBody
    public ResultVo save(Payment payment) {
        // 复制保留无需修改的数据
        if (payment.getId() != null) {
            Payment bePayment = paymentService.getById(payment.getId());
            EntityBeanUtil.copyProperties(bePayment, payment);
        }

        // 保存数据
        paymentService.save(payment);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 文章的稿费支付的单号记录界面
     */
    @GetMapping("/payRecord/{id}")
    public String toPayRecord(@PathVariable("id") Payment payment, Model model) {
        model.addAttribute("payment",payment);
        return "/system/payment/payRecord";
    }

    @PostMapping("/payed")
    @ResponseBody
    public String payed(@RequestParam(name = "id")Long id,
                          @RequestParam(name = "remark")String payedInfo) {
        Payment payment = paymentService.getById(id);
        payment.setRemark(payedInfo);
//        payment.setStatus((byte) 2);
        // 复制保留无需修改的数据
        if (payment.getId() != null) {
            Payment bePayment = paymentService.getById(payment.getId());
            EntityBeanUtil.copyProperties(bePayment, payment);
        }
        // 保存数据
        paymentService.save(payment);
        //得到相应的文章信息
        Article article = payment.getArticleID();
        String content = "您的'" + article.getTitle() + "'文章的稿费" + payment.getMoney() + "元已支付到预留的支付方式，请查收";
        //发送邮件提醒
        boolean flag = emailService.sendAttachmentMail(payment.getUserID().getEmail(),"来自《技术FAN》的通知消息：",content);
        if(!flag){
            System.out.println("邮件发送失败!");
        }
        //支付后给作者发送消息
        Information information = new Information();
        information.setTitle("稿费通知");
        information.setContent(content);
        information.setCreateDate(new Date());
        information.setUpdateDate(new Date());
        information.setUserID(article.getCreateBy().getId());
        information.setStatus((byte)0);

        //保存信息
        informationService.save(information);

        return "<h1>保存支付单号信息成功</h1>";
    }



    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("system:payment:detail")
    public String toDetail(@PathVariable("id") Payment payment, Model model) {
        model.addAttribute("payment",payment);
        return "/system/payment/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (paymentService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}